package uk.co.richardwkirk.parkrun.android.events.displays;

import java.util.ArrayList;

import uk.co.richardwkirk.parkrun.android.IntentExtras;
import uk.co.richardwkirk.parkrun.android.ParkrunEventData;
import uk.co.richardwkirk.parkrun.android.R;
import uk.co.richardwkirk.parkrun.android.events.RegionalEventGroup;
import uk.co.richardwkirk.parkrun.data.events.Event;
import uk.co.richardwkirk.parkrun.geo.Region;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;

public class EventSelection extends Activity {

	ArrayList<RegionalEventGroup> eventGroups;
	EventSelectionExpandableAdapter listAdapter;

	Region country = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.event_selection);

		// Get the Region to be displayed
		Intent intent = getIntent();
		String countryName = intent.getStringExtra(IntentExtras.EXTRA_SELECTED_COUNTRY);
		country = ParkrunEventData.getSingleton().getWorld().getRegion(countryName);
		this.setTitle(countryName + " (" + country.countEvents() + " events)");
		eventGroups = RegionalEventGroup.createFromCountry(country);

		ExpandableListView listView = (ExpandableListView) findViewById(R.id.event_list);
		listAdapter = new EventSelectionExpandableAdapter(getApplicationContext(), eventGroups);
		listView.setAdapter(listAdapter);
		listView.setOnChildClickListener(myListItemClicked);

		// Do we want to expand the groups? Only if 1 group only.
		if (listAdapter.getGroupCount() == 1) {
			listView.expandGroup(0);
		}
	}

	public void showOnMap(View view) {
		EventDisplay.startRegionDisplay(this, country);	
	}

	private void showEventDisplay(Event selectedEvent) {
		EventDisplay.startEventDisplay(this, selectedEvent);
	}
	
	// our child listener
	private OnChildClickListener myListItemClicked = new OnChildClickListener() {
		
		public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
			Event selectedEvent = (Event) listAdapter.getChild(groupPosition, childPosition);
			showEventDisplay(selectedEvent);
			return true;
		}

	};
	
}
